<template>
  <div class="box">
    <!-- 头部搜索模块 -->
    <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :buttonList="buttonList" />
    <!-- 中间表格模块 -->
    <BaseTable :data="collectiontableData" :columns="collectiontableDataColumns" :tableHeight="tableHeight"
      :pagination="true" :loading="loading" @details="selectDataList"></BaseTable>
    <div class="page">
      <div class="summary">
        <span>合计：</span>
        付款金额：<span style="color: #e0960d;">{{ summaryData.zamount ? summaryData.zamount : 0
        }}</span>&nbsp;&nbsp;&nbsp;&nbsp;
        剩余金额：<span style="color: #e0960d;">{{ summaryData.zsyje ? summaryData.zsyje : 0 }}</span>
      </div>
      <!-- <span></span> -->
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="totalNum">
      </el-pagination>
    </div>
    <!-- 新建信息 -->
    <el-drawer :before-close="handleClose" :title="title" :visible.sync="collectionInfomation" direction="rtl" size="30%">
      <addCollection ref="addCollection" :collectionMethodData="collectionMethodData" @upData="upData"
        :compData="compData" :customerData="customerData" />
      <div class="demo-drawer__footer" v-show="flagIneer">
        <el-button type="primary" @click="addSave" size="mini" :loading="ineerLoading">
          {{ ineerLoading ? "提交中 ..." : "保 存" }}
        </el-button>
        <el-button size="mini" @click="collectionInfomation = false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import dfilters from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/Business/collectionManagement'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
import addCollection from './addCollection.vue'
export default {
  name: 'ticketsManage',
  components: {
    BaseTable,
    headerSearch,
    addCollection
  },
  data() {
    return {
      // 新增/修改回款信息标题
      title: '',
      menuFlag: false, // 是否展示按钮
      tableHeight: window.innerHeight - 200,
      showSummary: true,
      // 搜索框显示对象
      selectObject: [
        {
          name: '组织',
          type: 'select',
          modelName: 'companyId',
          selectData: [],
          selectLabel: 'companyName',
          selectValue: 'companyId'
        },
        {
          name: '付款客户',
          type: 'select',
          modelName: 'customerId',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '状态',
          type: 'select',
          modelName: 'status',
          selectLabel: 'label',
          selectValue: 'value',
          selectData: [{
            value: '1',
            label: '未确认'
          }, {
            value: '2',
            label: '已确认'
          }]
        }
      ],
      // header的按钮list
      buttonList: [
        { label: '新建', type: 'primary', icon: 'el-icon-plus', click: () => this.addCollectionfomation, permission: 'basicDataSubsystem:collection:collectionInsert' },
        { label: '详情', type: 'primary', icon: 'el-icon-tickets', click: () => this.getDetails, permission: 'basicDataSubsystem:collection:collectionUpdate' },
        { label: '确认', type: 'primary', icon: 'el-icon-check', click: () => this.confirmClick, permission: 'basicDataSubsystem:collection:updateStatus' },
        { label: '撤销', disabled: false, type: 'primary', icon: 'el-icon-refresh-right', click: () => this.cancelClick, permission: 'basicDataSubsystem:collection:updateStatus' }
      ],
      collectiontableDataColumns: [ // table表头
        {
          prop: 'companyName',
          label: '组织',
          isShort: true
        },
        {
          prop: 'customerName',
          label: '付款客户',
          isShort: true
        },
        {
          prop: 'bankSerialNo',
          label: '流水号'
        },
        {
          prop: 'collectionDate',
          label: '交易时间'
        },
        {
          prop: 'amount',
          label: '付款金额',
          isMoney: true
        },
        {
          prop: 'syje',
          label: '剩余金额',
          isMoney: true
        },
        {
          prop: 'paymentAccount',
          label: '付款账号'
        },
        {
          prop: 'paymentType',
          label: '付款方式'
        },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            if (params.row.status == '1') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'danger'
                },
                domProps: {
                  innerHTML: '未确认'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'success'
              },
              domProps: {
                innerHTML: '已确认'
              }
            })
          }
        },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 200,
          render: (h, params) => {
            return h('div', [
              h('el-button', {
                props: {
                  size: 'mini',
                  disabled: params.row.status != '1'
                },

                domProps: {
                  // 添加标签,使用自己引入的iconfont图标
                  innerHTML:
                    "<span style='color:#0B6CD6'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>"
                },
                on: {
                  click: () => {
                    this.handleEditOut(params.row)
                  }
                }
              }),
              h('el-button', {
                props: {
                  size: 'mini',
                  disabled: params.row.status != '1'
                },

                domProps: {
                  // 添加标签,使用自己引入的iconfont图标
                  // innerHTML: `<i class="iconfont icon-tubiao_liebiaoshanchu" style="color:#DA2821"></i> 删除`
                  innerHTML: `<span style='color:#F75E5E'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                },
                on: {
                  click: () => {
                    this.handleDelete(params.row.id)
                  }
                }
              })
            ])
          }
        }
      ],
      collectiontableData: [], // table数据
      collectionMethodData: [], // 回款方式数据
      compData: [], // 业务单元数据
      customerData: [], // 客户数据
      formRules: {
        companyId: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        date1: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        date2: [
          { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
        ],
        type: [
          { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
        ],
        resource: [
          { required: true, message: '请选择活动资源', trigger: 'change' }
        ]
      },
      activeName: 'first',
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        portName: '',
        logogram: ''
      },
      totalNum: 0,
      drawerOut: false,
      flagOut: true,
      outForm: {
        portName: '',
        portCode: '',
        logogram: '',
        nationCode: '',
        sortNum: ''
      },
      flagIneer: true,
      collectionInfomation: false,
      portClassData: [],
      provinceData: [],
      cityData: [],
      oldOut: {},
      oldInner: {},
      outLoading: false,
      ineerLoading: false,
      // 使用情况
      usageDataColumns: [
        {
          prop: 'companyName',
          label: '结算单号'
        },
        {
          prop: 'customerName',
          label: '费目'
        },
        {
          prop: 'bankSerialNo',
          label: '船名航次'
        },
        {
          prop: 'collectionDate',
          label: '货名'
        },
        {
          prop: 'amount',
          label: '账单时间'
        },
        {
          prop: 'amount',
          label: '账单金额'
        },
        {
          prop: 'paymentAccount',
          label: '使用时间'
        },
        {
          prop: 'paymentType',
          label: '使用金额'
        },
        {
          prop: 'paymentType',
          label: '操作人'
        }
      ],
      detailsId: '',
      dataList: null,
      summaryData: {
        zamount: '',
        zsyje: ''
      }
    }
  },
  async activated() {
    this.getCustomer()
    this.getComp()
    this.getCollectionMethod()
  },
  methods: {
    /**
     * 新增回款信息
     */
    addCollectionfomation() {
      this.collectionInfomation = true
      this.flagIneer = true
      this.title = '新增回款信息'
      this.$nextTick(() => {
        this.$refs.addCollection.addData()
      })
    },
    /**
     * 新增回款信息保存
     */
    addSave() {
      this.$refs.addCollection.valiDate()
      this.detailsId = ''
    },
    // 新增/修改
    async upData() {
      const params = this.$refs.addCollection.formData
      if (this.title == '新增回款信息') {
        await api.reqAddCollections(params).then(res => {
          if (res.status == '200') {
            this.collectionInfomation = false
            this.$message.success('新增成功')
            this.getInnerList()
          }
        })
      } else {
        await api.reqCollectionsUpdate(params).then(res => {
          if (res.status == '200') {
            this.collectionInfomation = false
            this.$message.success('修改成功')
            this.getInnerList()
          }
        })
      }
    },
    /**
     * 获取客户信息
     */
    async getCustomer() {
      const res = await publicapi.getlistCustomer()
      this.customerData = res.data.data
      this.selectObject[1].selectData = this.customerData
    },
    /**
     * 获取业务单元
     */
    async getComp() {
      const res = await publicapi.getListComp()
      this.compData = res.data.data
      this.selectObject[0].selectData = this.compData
    },
    /**
     * 字典获取回款方式
     */
    async getCollectionMethod() {
      const res = await publicapi.getDictData('PAYMENT_METHOD')
      this.collectionMethodData = res.data.data.PAYMENT_METHOD
    },
    // 确认按钮
    confirmClick() {
      if (!this.detailsId) {
        return this.$message.error('请选择一条数据')
      }
      this.$confirm('确认修改？').then(() => {
        const data = {
          id: this.dataList.id,
          status: '2',
          amount: this.dataList.amount,
          syje: this.dataList.syje
        }
        api.changeStatus(data).then(res => {
          if (res.data.code == '0000') {
            this.getInnerList()
            return this.$message.success(res.data.msg)
          }
        })
      })
    },
    // 撤销按钮
    cancelClick() {
      if (!this.detailsId) {
        return this.$message.error('请选择一条数据')
      }
      this.$confirm('确认撤销？').then(() => {
        const data = {
          id: this.dataList.id,
          status: '1',
          amount: this.dataList.amount,
          syje: this.dataList.syje
        }
        api.changeStatus(data).then(res => {
          if (res.data.code == '0000') {
            this.getInnerList()
            return this.$message.success(res.data.msg)
          }
        })
      })
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.detailsId = ''
      this.getInnerList()
    },
    handleAcitveClick(tab) {
      this.queryAll.startpage = 1
      this.queryAll.pagesize = 10
      this.getInnerList()
    },
    // 获取数据
    async getInnerList() {
      this.loading = true
      this.summaryData.zamount = '0'
      this.summaryData.zsyje = '0'
      await api
        .reqGetCollections(this.queryAll)
        .then(res => {
          this.collectiontableData = res.data.data.pages
          if (this.collectiontableData.length > 0) {
            this.summaryData.zamount = this.formatMonenyNumber(this.collectiontableData[0].zamount)
            this.summaryData.zsyje = this.formatMonenyNumber(this.collectiontableData[0].zsyje)
            this.collectiontableData.forEach(item => {
              item.paymentType = this.collectionMethodData.filter(msg => msg.dictValue == item.paymentType)[0].dictLabel
              item.collectionDate = dfilters.getProcessingDate(item.collectionDate, '3')
            })
          }
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.totalNum = res.data.data.totalNum
          this.loading = false
        })
        .catch(() => { })
    },
    // 选中数据
    selectDataList(val) {
      this.detailsId = ''
      this.detailsId = val.id
      this.dataList = val
      if (this.dataList.amount != this.dataList.syje) {
        this.buttonList.filter(item => item.label == '撤销')[0].disabled = true
      } else {
        this.buttonList.filter(item => item.label == '撤销')[0].disabled = false
      }
    },
    /**
     * 编辑
     */
    async handleEditOut(row) {
      if (!this.collectionInfomation) {
        this.collectionInfomation = true
        this.flagIneer = true
      }
      await api.reqCollectionsById(row.id).then(res => {
        if (res.data.success) {
          const msg = res.data.data
          this.$refs.addCollection.updateData(msg)
        }
      })
      this.title = '修改回款信息'
    },
    // 详情请求
    async getDetails() {
      if (!this.detailsId) {
        return this.$message.error('请选择一条数据')
      }
      if (!this.collectionInfomation) {
        this.collectionInfomation = true
        this.flagIneer = true
      }
      await api.reqCollectionsById(this.detailsId).then(res => {
        if (res.data.success) {
          const msg = res.data.data
          this.$refs.addCollection.updateData(msg)
        }
      })
      this.title = '详情'
      this.flagIneer = false
      this.$refs.addCollection.notModified()
    },
    /**
     * 删除
     */
    async handleDelete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDeleteCollections(id).then(res => {
          if (res.data.code === '0000') {
            this.getInnerList()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 转化金额
    formatMonenyNumber(number) {
      const str = [];
      if (typeof number === 'number') {
        number = String(number)
      }
      if (number.length <= 3) {
        return number;
      }
      String(number).split('').reverse().forEach((item, index) => {
        if (index != 0 && index % 3 == 0) {
          str.push(',', item)
        } else {
          str.push(item)
        }
      })
      return str.reverse().join('');
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getInnerList()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getInnerList()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.collectionInfomation) {
        oldV = this.oldOut
        newV = this.outForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "../index.less";

.selectBox {
  justify-content: space-between;
  display: flex;
  background: #ffffff;
  border: 1px solid #c26a45;
  border-bottom: 0;
  border-left: none;
  height: 50px;
  position: relative;
  align-items: center;
  padding-left: 14px;
  padding-right: 20px;
}

.input_box {
  display: flex;
}

.page {
  background: #ffffff;
  text-align: right;
  border-radius: 0 0 4px 4px;
  padding: 5px 20px;

  .summary {
    position: absolute;
    left: 40px;
    margin-top: 5px;
  }
}

/deep/.el-tabs--border-card>.el-tabs__content {
  padding: 0 !important;
}

//抽屉底部样式
/deep/ .el-drawer__header {
  margin-bottom: 0;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}

.demo-drawer__footer {
  text-align: right;
  padding-right: 20px;
  border-top: 1px solid #c8cfde;
  background-color: #f5f7fa;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 50px;
}

.box {
  background: #ffffff;
  border: 1px solid #e1e4eb;
  border-radius: 4px 4px 0 0;
  border-top: none;
}
</style>
